package org.waigua.moka.processor;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Map;

import org.apache.commons.httpclient.HttpException;
import org.apache.log4j.Logger;
import org.waigua.moka.dto.ApiDto;
import org.waigua.moka.exception.SysException;
import org.waigua.moka.service.HttpApiService;
import org.waigua.moka.service.impl.HttpApiServiceImpl;
import org.waigua.moka.util.BigDecimalUtil;

public class UserInfoProcessor
{
	protected Logger log = Logger.getLogger(getClass());
	HttpApiService httpApiService = new HttpApiServiceImpl();

	public int getUserEnergy() throws SysException
	{
		try
		{
			Map<String, ?> userInfoMap = httpApiService.getUserinfo(ApiDto.buildApiDto());
			BigDecimal energy = new BigDecimal(String.valueOf(userInfoMap.get("Energy")));
			return energy.intValue();
		}
		catch (IllegalStateException e)
		{
			log.fatal("请求返回状态错误", e);
			return 0;
		}
		catch (NumberFormatException e)
		{
			log.fatal("请求返回Energy不为数字", e);
			return 0;
		}
		catch (HttpException e)
		{
			throw new SysException(e);
		}
		catch (IOException e)
		{
			throw new SysException(e);
		}
	}

	@SuppressWarnings("unchecked")
	public boolean chipFull() throws SysException
	{
		try
		{
			Map<String, ?> userInfoMap = httpApiService.getChips(ApiDto.buildApiDto());
			for (String key : userInfoMap.keySet())
			{
				Map<String, ?> chips = (Map<String, ?>) userInfoMap.get(key);
				log.info("chip info:" + chips.toString());
				if (BigDecimal.ZERO.compareTo(BigDecimalUtil.convert(chips.get("num"))) == 0)
				{
					return false;
				}
			}
		}
		catch (IllegalStateException e)
		{
			log.fatal("请求返回状态错误", e);
		}
		catch (NumberFormatException e)
		{
			log.fatal("请求返回Energy不为数字", e);
		}
		catch (HttpException e)
		{
			throw new SysException(e);
		}
		catch (IOException e)
		{
			throw new SysException(e);
		}
		return true;
	}
}
